#!/usr/bin/env python3
import req as requests
import json
from os.path import dirname, abspath, join


URL = "https://fred.stlouisfed.org/graph/fredgraph.csv?chart_type=line&recession_bars=on&log_scales=&bgcolor=%23e1e9f0&graph_bgcolor=%23ffffff&fo=Open+Sans&ts=12&tts=12&txtcolor=%23444444&show_legend=yes&show_axis_titles=yes&drp=0&cosd=1947-01-01&coed=2018-01-01&height=450&stacking=&range=&mode=fred&id=CPIAUCSL&transformation=lin&nd=1947-01-01&ost=-99999&oet=99999&lsv=&lev=&mma=0&fml=a&fgst=lin&fgsnd=2009-06-01&fq=Monthly&fam=avg&vintage_date=&revision_date=&line_color=%234572a7&line_style=solid&lw=2&scale=left&mark_type=none&mw=2&width=1168"

def main():
    r = requests.get(URL).content.decode("utf-8","ignore").split("\n")[1:]
    li = []
    for i in r:
        if not i:
            continue
        year, rate = i.split(",")
        rate = float(rate)
        li.append([year[:-3], rate])

    now = li[-1][-1]
    for i in li:
        i[-1] = now/i[-1]

    with open(join(dirname(abspath(__file__)), "fredgraph.json"),"w") as fredgraph:
        json.dump(li, fredgraph)

if __name__ == "__main__":
    main()

